import { Reducer } from 'redux';
import {
  ProgressState,
  initProgressState,
} from '../global-state-context.state';
import {
  ProgressAction,
  COMMON_UPDATE_FEATURE_PROGRESS,
  COMMON_CLEAR_FEATURE_PROGRESS,
} from '../action-type.const';
import MLog from '../../../util/main-log';

const TAG = 'ProgressReducer';

const progressReducer: Reducer<ProgressState, ProgressAction> = (
  state = initProgressState,
  action: ProgressAction
): ProgressState => {
  const { progressInfos } = state;
  switch (action.type) {
    case COMMON_UPDATE_FEATURE_PROGRESS:
      for (let i = 0; i < progressInfos.length; i += 1) {
        if (
          progressInfos[i].task.featureName ===
            action.progressInfo.task.featureName &&
          progressInfos[i].task.taskName === action.progressInfo.task.taskName
        ) {
          progressInfos[i].progress = action.progressInfo.progress;
          return { ...state, progressInfos };
        }
      }
      return state;
    case COMMON_CLEAR_FEATURE_PROGRESS:
      for (let i = 0; i < progressInfos.length; i += 1) {
        if (
          progressInfos[i].task.featureName ===
            action.progressInfo.task.featureName &&
          progressInfos[i].task.taskName === action.progressInfo.task.taskName
        ) {
          progressInfos[i].progress = 0;
          return { ...state, progressInfos };
        }
      }
      return state;
    default:
      return state;
  }
};

export default progressReducer;
